// 文件上传处理
document.addEventListener('DOMContentLoaded', function() {
    const fileUploadArea = document.getElementById('file-upload-area');
    const fileInput = document.getElementById('file-input');
    const convertBtn = document.getElementById('convert-btn');
    const qualitySlider = document.getElementById('quality-slider');
    const qualityValue = document.getElementById('quality-value');
    const compressBtn = document.getElementById('compress-btn');

    // 文件上传区域点击事件
    fileUploadArea.addEventListener('click', () => {
        fileInput.click();
    });

    // 文件拖放处理
    fileUploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        fileUploadArea.classList.add('dragover');
    });

    fileUploadArea.addEventListener('dragleave', () => {
        fileUploadArea.classList.remove('dragover');
    });

    fileUploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        fileUploadArea.classList.remove('dragover');
        const files = e.dataTransfer.files;
        handleFiles(files);
    });

    // 文件选择处理
    fileInput.addEventListener('change', (e) => {
        handleFiles(e.target.files);
    });

    // 压缩质量滑块
    qualitySlider.addEventListener('input', (e) => {
        qualityValue.textContent = `${e.target.value}%`;
    });

    // 文件处理函数
    function handleFiles(files) {
        if (files.length > 0) {
            const file = files[0];
            // 显示文件名
            fileUploadArea.innerHTML = `<p>已选择: ${file.name}</p>`;
            // 如果是图片，显示预览
            if (file.type.startsWith('image/')) {
                previewImage(file, document.getElementById('original-image'));
            }
        }
    }

    // 图片预览函数
    function previewImage(file, element) {
        const reader = new FileReader();
        reader.onload = (e) => {
            element.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }

    // 文件转换处理
    convertBtn.addEventListener('click', async () => {
        const file = fileInput.files[0];
        const targetFormat = document.getElementById('target-format').value;
        
        if (!file) {
            alert('请先选择文件');
            return;
        }

        if (!targetFormat) {
            alert('请选择目标格式');
            return;
        }

        // 验证文件类型
        const allowedTypes = [
            'text/plain',
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        ];

        if (!allowedTypes.includes(file.type)) {
            alert('不支持的文件类型，请上传TXT、PDF、DOC或DOCX文件');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('targetFormat', targetFormat);

        try {
            // 显示加载状态
            convertBtn.disabled = true;
            convertBtn.textContent = '转换中...';
            document.getElementById('convert-result').classList.add('d-none');
            document.getElementById('error-message').classList.add('d-none');

            const response = await fetch('/api/convert', {
                method: 'POST',
                body: formData
            });

            const data = await response.json();
            
            if (data.success) {
                // 显示转换结果
                const resultDiv = document.getElementById('convert-result');
                resultDiv.classList.remove('d-none');
                
                // 更新下载链接
                const downloadBtn = document.getElementById('download-btn');
                downloadBtn.href = data.downloadUrl;
                downloadBtn.textContent = `点击下载${targetFormat.toUpperCase()}文件`;
                downloadBtn.classList.add('btn', 'btn-primary', 'mt-3');
                
                // 显示文件信息
                const fileInfo = document.createElement('p');
                fileInfo.textContent = `文件已成功转换为${targetFormat.toUpperCase()}格式，点击上方按钮下载。`;
                fileInfo.classList.add('mt-2');
                
                // 清空之前的内容并添加新内容
                resultDiv.innerHTML = '';
                resultDiv.appendChild(downloadBtn);
                resultDiv.appendChild(fileInfo);
            } else {
                // 显示错误信息
                document.getElementById('error-message').textContent = data.message;
                document.getElementById('error-message').classList.remove('d-none');
            }
        } catch (error) {
            console.error('Error:', error);
            document.getElementById('error-message').textContent = '转换过程中发生错误: ' + error.message;
            document.getElementById('error-message').classList.remove('d-none');
        } finally {
            // 恢复按钮状态
            convertBtn.disabled = false;
            convertBtn.textContent = '开始转换';
        }
    });

    // 图片压缩处理
    compressBtn.addEventListener('click', async () => {
        const file = fileInput.files[0];
        const quality = qualitySlider.value;

        if (!file) {
            alert('请先选择图片');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('quality', quality);

        try {
            compressBtn.disabled = true;
            compressBtn.textContent = '压缩中...';

            const response = await fetch('/api/image/compress', {
                method: 'POST',
                body: formData
            });

            const data = await response.json();
            
            if (data.success) {
                document.getElementById('compressed-image').src = data.previewUrl;
                document.getElementById('download-btn').href = data.downloadUrl;
            } else {
                alert('压缩失败: ' + data.message);
            }
        } catch (error) {
            console.error('Error:', error);
            alert('压缩过程中发生错误');
        } finally {
            compressBtn.disabled = false;
            compressBtn.textContent = '开始压缩';
        }
    });
}); 